package com.bear.fastrepair.mvvm.ui.employee.fragment

import android.text.InputType
import android.text.TextUtils
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.bear.fastrepair.R
import com.bear.fastrepair.base.BaseFragment
import com.bear.fastrepair.databinding.FragmentResetPasswordBinding
import com.bear.fastrepair.entity.ResetPasswordBean
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModel
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModelFactory
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils

/**
 * @description
 * @author jacky
 * @date 2021/11/24-18:17
 */
class EmployeeResetPasswordFragment : BaseFragment<FragmentResetPasswordBinding>() {

    private lateinit var viewModel: EmployeeViewModel

    override val title: String
        get() = "重置密码"

    override fun init() {
        viewModel = ViewModelProvider(
            requireActivity(),
            EmployeeViewModelFactory()
        ).get(EmployeeViewModel::class.java)

        viewModel.resetPassword.observe(viewLifecycleOwner) {
            if (it.code == -1) return@observe
            if (it.code == 0) {
                ToastUtils.showShort("重置密码成功")
                findNavController().popBackStack()
                findNavController().navigate(R.id.employeeOrderFragment)
            } else {
                ToastUtils.showShort("重置密码失败，${it.msg}")
            }
            viewModel.resetPassword.value?.code = -1
        }

        binding.include.toolbarTitle.text = title
        binding.include.toolbarBack.setOnClickListener { findNavController().popBackStack() }

        binding.btnConfirm.setOnClickListener {
            val password = binding.password.text.toString()
            val confirmPassword = binding.confirmPassword.text.toString()
            LogUtils.i("password $password confirmPassword $confirmPassword")
            if (!TextUtils.equals(password, confirmPassword)) {
                ToastUtils.showShort("两次输入密码不一致，请重新输入")
                return@setOnClickListener
            }
            val id = viewModel.personalInfo.value?.data?.id
            viewModel.resetPassword(ResetPasswordBean(id, password, confirmPassword))
        }

        binding.cbShowPassword.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) binding.password.inputType =
                InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
            else binding.password.inputType =
                InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        }

        binding.cbShowPasswordConfirm.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) binding.confirmPassword.inputType =
                InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
            else binding.confirmPassword.inputType =
                InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
        }
    }
}